package com.customization.unionpay.market.job;

import com.alibaba.fastjson.JSONObject;
import com.customization.unionpay.market.util.FormDataUtils;
import com.customization.unionpay.market.util.PropUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;
import weaver.interfaces.schedule.BaseCronJob;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * @author sjm
 * @description 定时符合条件的预付款台账数据推送流程
 */
public class SyncPushFinancialCompletionLedgerJob  extends BaseCronJob {

    private static final Logger log = LoggerFactory.getLogger(SyncPushFinancialCompletionLedgerJob.class);

    @Override
    public void execute() {

        RecordSet rs = new RecordSet();
        try {
            // 财务事项结束流程id
            String workId = com.customization.unionpay.market.util.PropUtils.BB_LOG.getPropValue("marketSubject", "cwsxjs_work_id");
            log.info("workId："+workId);
            // 财务事项申请url
            String cwsxjsUrl = com.customization.unionpay.market.util.PropUtils.BB_LOG.getPropValue("marketSubject", "cwsxjs_url");
            log.info("cwsxjsUrl："+cwsxjsUrl);

            String isNext = "0";

            // 营销预付活动台账表单id
            int marketingPrepaidActivityLedgerFormId = Integer.parseInt(com.customization.unionpay.market.util.PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_prepaid_activity_ledger_form_id"));
            String isNot = com.customization.unionpay.market.util.FormDataUtils.getItemValue(marketingPrepaidActivityLedgerFormId, "cwsfjs", "否");

            String maintablename = com.customization.unionpay.market.util.FormDataUtils.getTableName(marketingPrepaidActivityLedgerFormId);
            log.info("营销预付活动台账表单："+maintablename);

            // 营销活动事项台账表单id
            int formId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_activity_ledger_form_id"));
            String tablename = com.customization.unionpay.market.util.FormDataUtils.getTableName(formId);
            log.info("营销活动事项台账表单："+tablename);

            String selectValueYes = com.customization.unionpay.market.util.FormDataUtils.getItemValue(formId, "hdsfhx", "是");
            log.info("活动是否核销 是："+selectValueYes);

            StringBuilder sql = new StringBuilder("select id,yxpthdsqm,jbr from ");
            sql.append(maintablename);
            sql.append(" where cwsfjs='");
            sql.append(isNot);
            sql.append("' and yfkjy='");
            sql.append(0);
            sql.append("' and (sftstx='' or sftstx is null)");

            log.info("查询sql:"+sql.toString());

            rs.executeQuery(sql.toString());

            while (rs.next()){
                String id = Util.null2String(rs.getString("id"));
                log.info("id:"+id);
                String yxpthdsqm = Util.null2String(rs.getString("yxpthdsqm"));
                String jbr = Util.null2String(rs.getString("jbr"));
                log.info("jbr:"+jbr);
                if(!("").equals(yxpthdsqm) && !("").equals(id) && !("").equals(jbr)){
                    User user = new User();
                    user.setUid(Integer.valueOf(jbr));
                    boolean b = com.customization.unionpay.market.util.FormDataUtils.selectSfhx(tablename, yxpthdsqm, selectValueYes);
                    if(b) {
                        log.info("yxpthdsqm:"+yxpthdsqm);
                        JSONObject json = new JSONObject();

                        JSONObject jbrz = new JSONObject();
                        jbrz.put("name", "jbr");
                        jbrz.put("type", "");
                        jbrz.put("value", jbr);
                        json.put("jbr", jbrz);

                        JSONObject yxpthdsqmz = new JSONObject();
                        yxpthdsqmz.put("name", "yxpthdsqm");
                        yxpthdsqmz.put("type", "");
                        yxpthdsqmz.put("value", yxpthdsqm);
                        json.put("yxpthdsqm", yxpthdsqmz);

                        log.info("size:"+json.size());
                        // 主表字段长度
                        int size = json.size();
                        long time = new Date().getTime();
                        log.info("time:"+time);
                        String requestid = com.customization.unionpay.market.util.FormDataUtils.createWorkFlow(user, json, size, 0, workId, isNext, "0", "营销预付活动台账财务事项结束提醒-" + yxpthdsqm);
                        log.info("requestid:"+requestid);
                        cwsxjsUrl = cwsxjsUrl.replaceAll("#time#", String.valueOf(time));
                        cwsxjsUrl = cwsxjsUrl.replaceAll("#requestId#", requestid);
                        log.info("cwsxjsUrl:" + cwsxjsUrl);

                        Set<String> users = new HashSet<>();
                        users.add(jbr);
                        FormDataUtils.putWarningMessageInfo(users, "营销预付活动台账财务事项结束提醒", "营销预付活动台账财务事项结束提醒-" + yxpthdsqm, cwsxjsUrl, null);
                        log.info("updateSftstx！");
                        updateSftstx(maintablename, yxpthdsqm);
                    }else {
                        log.info("当前未核销！");
                    }
                }
            }
        } catch (Exception e) {
            log.error("定时任务异常：" + e.getMessage());
        }
    }

    public void updateSftstx(String tableName,String code){

        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);
        try {
            StringBuilder updateSql = new StringBuilder(" update ");
            updateSql.append(tableName);
            updateSql.append(" set sftstx='");
            updateSql.append("已推送");
            updateSql.append("'  where yxpthdsqm ='");
            updateSql.append(code);
            updateSql.append("' ");
            log.info("updateSql:" + updateSql.toString());
            // 修改营销活动事项台账 已使用金额 sum(台账明细*清算金额），已入账金额 sum(明细数据.入账金额），已请款金额 sum(明细数据.请款金额）
            rst.executeUpdate(updateSql.toString());
            // 提交事务
            rst.commit();
        } catch (Exception e) {
            // 回滚
            rst.rollback();
            log.error("修改数据异常：" + e.getMessage());
        }
    }
}
